import { asyncRoutes, constantRoutes } from "@/router";

/**
 * @param {array} menus 用户菜单列表
 * @param {object} route 路由信息
 * @returns {boolean} 是否拥有此路由权限
 */
function hasPermission(menus, route) {
  if (route.meta && route.meta.roles) {
    return menus.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * @param {array} routes 定义的所有动态路由
 * @param {array} menus 用户菜单列表
 * @returns {array} 过滤完成的动态路由
 */
function filterAsyncRoutes(routes, menus) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(menus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus);
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  routes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  generateRoutes({ commit }, menus) {
    return new Promise((resolve) => {
      let accessRoutes = filterAsyncRoutes(asyncRoutes, menus);
      commit("SET_ROUTES", accessRoutes);
      resolve(accessRoutes);
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
